from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_protect
from .models import GradingItem

def index(request):
    """展示所有评分标准列表"""
    grading_items = GradingItem.objects.all()
    return render(request, 'index.html', {
        'grading_items': grading_items,
        'title': '评分标准管理'
    })

@csrf_protect
def update_item(request):
    """处理评分项的更新请求"""
    if request.method == 'POST':
        try:
            # 获取请求数据
            item_id = request.POST.get('id')
            item_name = request.POST.get('item_name')
            max_score = request.POST.get('max_score')
            description = request.POST.get('description')

            # 获取对应的评分项
            try:
                grading_item = GradingItem.objects.get(id=item_id)
            except GradingItem.DoesNotExist:
                return JsonResponse({
                    'status': 'error',
                    'message': '评分项不存在'
                })

            # 验证并更新字段值
            if not item_name:
                return JsonResponse({
                    'status': 'error',
                    'message': '评价点不能为空'
                })
            
            try:
                max_score = int(max_score)
                if max_score <= 0:
                    raise ValueError
            except ValueError:
                return JsonResponse({
                    'status': 'error',
                    'message': '最高分值必须是正整数'
                })
            
            if not description:
                return JsonResponse({
                    'status': 'error',
                    'message': '评价描述不能为空'
                })

            # 更新所有字段
            grading_item.item_name = item_name
            grading_item.max_score = max_score
            grading_item.description = description
            grading_item.save()

            return JsonResponse({
                'status': 'success',
                'message': '保存成功'
            })

        except Exception as e:
            return JsonResponse({
                'status': 'error',
                'message': str(e)
            })

    # 非POST请求返回错误
    return JsonResponse({
        'status': 'error',
        'message': '仅支持POST请求'
    })